package com.atguigu.state;

import com.atguigu.bean.WaterSensor;
import com.atguigu.utils.MyUtils;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * Created by RUI on 2021/6/15 18:28
 *
 * 去重: 去掉重复的水位值. 思路: 把水位值作为MapState的key来实现去重, value随意
 */
public class State_map {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        env.socketTextStream("hadoop162",9999)
                .map(value -> {
                    String[] split = value.split(",");
                    return new WaterSensor(split[0],Long.valueOf(split[1]),Integer.valueOf(split[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private MapState<Integer, Object> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<Integer, Object>(
                                "mapState",
                                Integer.class,
                                Object.class

                        ));
                    }

                    @Override
                    public void processElement(WaterSensor ws, Context ctx, Collector<String> out) throws Exception {

                        mapState.put(ws.getVc(),new Object());

                        Iterable<Integer> keys = mapState.keys();
                        List<Integer> toList = MyUtils.toList(keys);

                        out.collect(ctx.getCurrentKey()+": " + toList.toString());

                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
